package com.xin.beauty.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xin.beauty.mapper.RolePermissionMapper;
import com.xin.beauty.pojo.entity.Permission;
import com.xin.beauty.mapper.PermissionMapper;
import com.xin.beauty.pojo.entity.RolePermission;
import com.xin.beauty.pojo.vo.PermissionVO;
import com.xin.beauty.pojo.vo.RouterVO;
import com.xin.beauty.service.IPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Xin
 * @since 2025-04-29
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public List<PermissionVO> selectPermissionTree() {
        //1.查找所有权限，返回list集合
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("sort");
        List<Permission> permissionList = permissionMapper.selectList(queryWrapper);

        List<PermissionVO> permissionVOList = new ArrayList<>();
        permissionList.forEach(permission -> {
            PermissionVO permissionVO = new PermissionVO();
            BeanUtils.copyProperties(permission, permissionVO);
            permissionVOList.add(permissionVO);
        });

        List<PermissionVO> permissionVOTree = buildTree(permissionVOList);
        return permissionVOTree;
    }

    @Override
    public Map<String, Object> selectAssignedPermission(Long roleId) {
        List<PermissionVO> permissionVOList = selectPermissionTree();
        //根据角色roleId查询这个角色下面已经分配的所有权限
        QueryWrapper<RolePermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId).select("permission_id");
        List<RolePermission> assignedRolePermissionList = rolePermissionMapper.selectList(queryWrapper);
        List<Long> assignedPermissionIdList = new ArrayList<>();
        for (RolePermission rolePermission : assignedRolePermissionList) {
            assignedPermissionIdList.add(rolePermission.getPermissionId());
        }

        Map<String, Object> map = new HashMap<>();
        map.put("permissionVOList", permissionVOList);
        map.put("assignedPermissionIdList", assignedPermissionIdList);
        return map;
    }

    @Override
    public void assignPermission(Long roleId, Long[] permissionIds) {
        rolePermissionMapper.delete(new QueryWrapper<RolePermission>().eq("role_id", roleId));
        for (Long permissionId : permissionIds) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            rolePermissionMapper.insert(rolePermission);
        }
    }

    @Override
    public List<RouterVO> selectRouterTreeByAdminId(Integer id) {
        //1.查找用户所有的权限
        List<Permission> permissionList = permissionMapper.selectPersmissionByAdminId(id);
        List<PermissionVO> permissionVOList = new ArrayList<>();
        permissionList.forEach(permission -> {
            PermissionVO permissionVO = new PermissionVO();
            BeanUtils.copyProperties(permission, permissionVO);
            permissionVOList.add(permissionVO);
        });

        List<PermissionVO> permissionVOTree = buildTree(permissionVOList);
        //转转成路由结构
        List<RouterVO> routerTreeList = buildRouterTree(permissionVOTree);

        return routerTreeList;
    }

    private List<RouterVO> buildRouterTree(List<PermissionVO> permissionVOTree) {
        List<RouterVO> routerTreeList = new ArrayList<>();
        //首先遍历一级目录
        for (PermissionVO permissionVO : permissionVOTree) {
            RouterVO routerVO = new RouterVO();
            routerVO.setName(permissionVO.getName());
            routerVO.setIcon(permissionVO.getIcon());
            routerVO.setPath(permissionVO.getPath());
            List<PermissionVO> childPermissionVO = permissionVO.getChildren();
            if (!CollectionUtils.isEmpty(childPermissionVO) && permissionVO.getType() == 0) {
                List<RouterVO> children = new ArrayList<>();
                for (PermissionVO permission : childPermissionVO) {
                    RouterVO router = new RouterVO();
                    router.setName(permission.getName());
                    router.setIcon(permission.getIcon());
                    router.setPath(permission.getPath());
                    children.add(router);
                }
                routerVO.setChildren(children);
            }
            routerTreeList.add(routerVO);
        }
        return routerTreeList;
    }

    @Override
    public List<String> selectBtnListByAdminId(Integer id) {
        List<Permission> permissionList = permissionMapper.selectPersmissionByAdminId(id);
        List<String> btnList = new ArrayList<>();
        for (Permission permission : permissionList) {
            if (permission.getType() == 2) {
                btnList.add(permission.getPermissionValue());
            }
        }
        return btnList;
    }

    private List<PermissionVO> buildTree(List<PermissionVO> permissionVOList) {
        //返回的树形结构集合中每个元素是parentId=0
        List<PermissionVO> treeList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(permissionVOList)) {
            for (PermissionVO permissionVO : permissionVOList) {
                if (permissionVO.getParentId() == 0) {
                    permissionVO.setChildren(buildChildTree(permissionVO, permissionVOList));
                    treeList.add(permissionVO);
                }
            }
        }

        return treeList;
    }

    /**
     * 在所有集合里面查找 permissionVO的孩子的集合
     * @param permissionVO
     * @param permissionVOList
     * @return
     */
    private List<PermissionVO> buildChildTree(PermissionVO permissionVO, List<PermissionVO> permissionVOList) {
        List<PermissionVO> children = new ArrayList<>();
        if (!CollectionUtils.isEmpty(permissionVOList)) {
            for (PermissionVO permission : permissionVOList) {
                if (permission.getParentId().longValue() == permissionVO.getId().longValue()) {
                    permission.setChildren(buildChildTree(permission, permissionVOList));
                    children.add(permission);
                }
            }
        }
        return children;
    }

}
